import { ElMessage } from 'element-plus'
import { LoginApi } from './api'
import { ConfigClass } from './config'
import { useRouter } from 'vue-router'
import { ref } from 'vue'

export class LoginClass {
	configClass: ConfigClass
	commonForm
	private router = useRouter()
	isRegistry = ref<boolean>(false)
	constructor(commonForm) {
		this.configClass = new ConfigClass()
		this.commonForm = commonForm
	}

	/**
	 * 获取登录配置
	 */
	public getFormCol() {
		return this.configClass.formCol
	}

	/**
	 * 登录
	 */
	public login(isRegistry: boolean) {
		this.commonForm.value.validForm().then(() => {
			const formData = this.commonForm.value.getFormData()
			const params = {
				...formData
			}
			if (isRegistry) {
				LoginApi.registry(params).subscribe(() => {
					ElMessage.success('注册成功')
					this.isRegistry.value = false
				})
				return
			}
			LoginApi.login(params).subscribe(res => {
				localStorage.setItem('token', res)
				ElMessage.success('登录成功')
				localStorage.setItem('username', formData.username)
				this.router.push({ name: 'WorkSpace' })
			})
		})
	}

	/**
	 * 注册
	 */
	public registry() {
		this.isRegistry.value = true
		this.commonForm.value.resetForm()
	}
}
